package com.guang.lock.interupt;

import java.util.concurrent.TimeUnit;

/**
 * @Description
 * @Author liguang
 * @Date 2023/06/20/17:21
 */
public class TestInteruptOne {
    static  boolean flag = false;
    public static void main(String[] args) throws InterruptedException {
        Thread threaA = new Thread(() -> {
            boolean flagTmp = flag;
            while (!flagTmp){

            }
            System.out.println("flag变量可见了");
        }, "threaA");

        Thread threaB = new Thread(() -> {
            while (!flag){
            }
            System.out.println("flag变量可见了");
        }, "threaB");

        threaA.start();
        threaB.start();
        TimeUnit.SECONDS.sleep(2);
        flag = true;
        TimeUnit.SECONDS.sleep(2);
        System.out.println("main end");
    }

    private static void testTwo() throws InterruptedException {
        Thread threadA = new Thread(() -> {
            System.out.println("当前线程是:"+Thread.currentThread().getName());
            while (true){
                if (Thread.currentThread().isInterrupted()){
                    System.out.println("当前线程被中断了");
                }
            }
        }, "threadA");

        threadA.start();
        TimeUnit.SECONDS.sleep(3);
        threadA.interrupt();
        System.out.println("当前线程"+Thread.currentThread().getName()+"   end ");
    }

    private static void testOne() throws InterruptedException {
        Thread threadA = new Thread(() -> {
            System.out.println("当前线程是:"+Thread.currentThread().getName());
            if (!Thread.currentThread().isInterrupted()){
                try {
                    TimeUnit.SECONDS.sleep(5);
                } catch (InterruptedException e) {
                    boolean interruptedFlag = Thread.currentThread().isInterrupted();
                    System.out.println("线程被中断?"+interruptedFlag);
                }
            }
        }, "threadA");

        threadA.start();
        TimeUnit.SECONDS.sleep(3);
        threadA.interrupt();
        System.out.println("当前线程"+Thread.currentThread().getName()+"   end ");
    }
}
